package com.szdvte.news.action.service;

import java.util.ArrayList;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.szdvte.news.bean.Users;
import com.szdvte.news.service.IUserService;
import com.szdvte.news.util.StringUtils;

public class UserAction extends BaseAction
{
	private Users user;
	private IUserService userService;
	private List<Users> userlist = new ArrayList<Users>();
	
	public String login()
	{
		if(user==null)
		{
			return "no";
		}
		
		if(StringUtils.isBlank(user.getUserName()))
		{
			return "no";
		}
		
		if(StringUtils.isBlank(user.getUserPassword()))
		{
			return "no";
		}
		
		user.setUserFlag(2);
		user = userService.login(user);
		ServletActionContext.getContext().getSession().put("user", user);
		
		if(user != null)
		{
			return "ok";
		}
		else
		{
			return "no";
		}
	}
	
	public String logout()
	{
		ServletActionContext.getRequest().getSession().removeAttribute("user");
		return "no";
	}
	
	public String select()
	{
		showUsers();
	    return "user";
	}
	
	public String add()
	{
		this.setFlag(1);
		user.setUserPhoto("images/temp.png");
		user.setUserNumber("");
		user.setUserAddress("");
		user.setUserFlag(2);
		if(userService.add(user).equals("注册成功"))
		{
			this.setFlag(2);
		}
		else
		{
			this.setFlag(3);
		}
		return "add";
	}
	
	public String load()
	{
		user = userService.load(user);
		return "load";
	}
	
	public String update()
	{
		this.setFlag(1);
		if(userService.update(user)){
			this.setFlag(2);
		}else{
			this.setFlag(3);
		}
		return "load";
	}
	
	public String delete()
	{
		this.setFlag(1);
		if(userService.delete(user)){
			this.setFlag(2);
		}else{
			this.setFlag(3);
		}
		showUsers();
	    return "user";
	}
	
	private void showUsers()
	{
		userlist = userService.select();
		ServletActionContext.getContext().getSession().put("userList", userlist);
	}
	
	public Users getUser() 
	{
		return user;
	}
	
	public void setUser(Users user) 
	{
		this.user = user;
	}
	
	public IUserService getUserService() 
	{
		return userService;
	}
	
	public void setUserService(IUserService userService) 
	{
		this.userService = userService;
	}
	
	public List<Users> getUserlist() 
	{
		return userlist;
	}
	
	public void setUserlist(List<Users> userlist) 
	{
		this.userlist = userlist;
	}
}
